var board = document.getElementById("board");
var canvas = document.getElementById("game");
var ctx = canvas.getContext("2d");

var KEYS = {
    37: 'left',
    38: 'up',
    39: 'right',
    40: 'down',
    32: 'shoot'
};

var tank = new Tank({
    centerX: 100,
    centerY: canvas.height - 100,
    direction: null,
    towards: "right"
});
var enemy = new Tank({
    centerX: canvas.width - 100,
    centerY: 100,
    direction: null,
    towards: "down"
});
enemy.action = action;

var bullets = [];
var tanks = [tank, enemy];

function rerender() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    bullets.forEach(function(bullet) {
        bullet.draw();
    });
    tanks.forEach(function(tank) {
        tank.draw();
    });
}

document.addEventListener("keydown", function(e) {
    var direction = KEYS[e.keyCode];
    if(!direction) {
        if(e.keyCode === 13) {
            run();
            rerender();
        }
    } else if(direction === "shoot") {
        tank.shoot();
    } else {
        tank.direction = direction;
    }
});

function disappear(sprites, sprite) {
    var i = sprites.indexOf(sprite);
    sprites.splice(i, 1);
}

function run() {
    board.innerHTML =
        "<p>坦克数：" + tanks.length + "</p>" +
        "<p>子弹数：" + bullets.length + "</p>";
    rerender();
    tanks.forEach(function(tank) {
        tank.action();
        tank.move();
    });
    bullets.forEach(function(bullet) {
        bullet.move();
        tanks.forEach(function(tank) {
            if(bullet.isIntersecting(tank)) {
                disappear(tanks, tank);
                disappear(bullets, bullet);
            }
        });
    });
    tank.direction = null;
}

rerender();
setInterval(run, 1000 / 30);
